#include "ScintillaView.h"
#include "Scintilla.h"
#include "WcharMbcsConvertor.h"

#include <exception>

ScintillaView::ScintillaView(void)
	: Window(),_pScintillaFunc(NULL),_pScintillaPtr(NULL)
{
}


ScintillaView::~ScintillaView(void)
{
}

void ScintillaView::init(HINSTANCE hInst, HWND parent)
{
	Window::init(hInst, parent);
	_hSelf = ::CreateWindowEx(
		WS_EX_CLIENTEDGE,\
		TEXT("Scintilla"),\
		TEXT("LogHelpView"),\
		WS_CHILD | WS_VSCROLL | WS_HSCROLL | WS_CLIPCHILDREN | WS_EX_RTLREADING,\
		0, 0, 100, 100,\
		_hParent,\
		NULL,\
		_hInst,\
		NULL);

	if (!_hSelf)
	{
		throw std::exception("ScintillaEditView::init : CreateWindowEx() function return null");
	}

	_pScintillaFunc = (SCINTILLA_FUNC)::SendMessage(_hSelf, SCI_GETDIRECTFUNCTION, 0, 0);
	_pScintillaPtr = (SCINTILLA_PTR)::SendMessage(_hSelf, SCI_GETDIRECTPOINTER, 0, 0);

	if (!_pScintillaFunc)
	{
		throw std::exception("ScintillaEditView::init : SCI_GETDIRECTFUNCTION message failed");
	}

	if (!_pScintillaPtr)
	{
		throw std::exception("ScintillaEditView::init : SCI_GETDIRECTPOINTER message failed");
	}

}

LRESULT ScintillaView::execute(UINT Msg, WPARAM wParam /* = 0 */, LPARAM lParam /* = 0 */) const
{
	return _pScintillaFunc(_pScintillaPtr, static_cast<int>(Msg), static_cast<int>(wParam), static_cast<int>(lParam));
}

void ScintillaView::setReadOnly(bool isReadOnly) const
{
	execute(SCI_SETREADONLY, isReadOnly);
}

void ScintillaView::addGenericText(const TCHAR * text2Append) const
{
	WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
	unsigned int cp = execute(SCI_GETCODEPAGE); 
	const char *text2AppendA =wmc->wchar2char(text2Append, cp);
	execute(SCI_ADDTEXT, strlen(text2AppendA), (LPARAM)text2AppendA);
}